<template>
  <div class="studentEdit">
    <el-form v-loading="loading" :model="form" label-width="auto" style="max-width: 600px" :rules="rules">
      <el-form-item label="年级:" prop="gradeLevel">
        <el-select v-model="form.gradeLevel" clearable @change="handleChange">
          <el-option label="一年级" :value="1" />
          <el-option label="二年级" :value="2" />
          <el-option label="三年级" :value="3" />
          <el-option label="四年级" :value="4" />
          <el-option label="五年级" :value="5" />
          <el-option label="六年级" :value="6" />
          <el-option label="初一" :value="7" />
          <el-option label="初二" :value="8" />
          <el-option label="初三" :value="9" />
          <el-option label="高一" :value="10" />
          <el-option label="高二" :value="11" />
          <el-option label="高三" :value="12" />
        </el-select>
      </el-form-item>

      <el-form-item label="学科:" prop="subjectId">
        <el-select v-model="form.subjectId">
          <el-option v-for="item in selectSubject" :key="item.id" :label="`${item.name}(${item.levelName})`"
            :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="题干:" prop="title">
        <el-input v-model="form.title" @click="handleShow('title')" />
      </el-form-item>

      <el-form-item label="选项:" prop="items">
        <div v-for="(item, index) in form.items" :key="item.prefix"
          style="display: flex; width: 500px; margin-bottom: 10px;">
          <div style="padding: 5px 10px;">{{ item.prefix }}</div>
          <el-input v-model="item.content"></el-input>
          <el-button type="danger" :icon="Delete" style="width: 46px; height: 42px; margin-left: 10px;"
            @click="deleteItem(index)"></el-button>
        </div>
      </el-form-item>

      <el-form-item label="解析:" prop="analyze">
        <el-input v-model="form.analyze" @click="handleShow('analyze')"></el-input>
      </el-form-item>

      <el-form-item label="分数:" prop="score">
        <el-input-number v-model="form.score" />
      </el-form-item>

      <el-form-item label="难度:" prop="difficult">
        <el-rate v-model="form.difficult" />
      </el-form-item>

      <el-form-item label="正确答案:" prop="correct">
        <el-radio-group v-model="form.correct">
          <el-radio v-for="item in form.items" :key="item.prefix" :value="item.prefix">{{ item.prefix
          }}</el-radio>
        </el-radio-group>
      </el-form-item>


      <el-form-item label="   ">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="success" @click="add">添加选项</el-button>
        <el-button type="success" @click="resetForm">预览</el-button>
      </el-form-item>
    </el-form>


    <el-dialog v-model="dialogVisible" width="500">
      <!-- 富文本编辑器 -->
      <UEditor :key="flag" @ready="editorReady"></UEditor>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>


  </div>

</template>


<script setup lang="ts">
import UEditor from '@/components/UEditor.vue'
import ExamAPI, { QuestionAddType, SubjectResponse, AnswerType } from '@/api/system/exam.api'
import { Delete } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const loading = ref(false)

let form = ref<QuestionAddType>({
  id: null, //题目id
  questionType: 1, //题型
  subjectId: null, //学科
  title: "", //题干
  gradeLevel: null, //年级
  analyze: "", //解析
  correctArray: [], //标签
  correct: "", //正确答案
  score: 0, //题目分数
  difficult: 0, //难度
  items: [
    {
      prefix: "A", //65
      content: ""
    },
    {
      prefix: "B", //66
      content: ""
    },
    {
      prefix: "C", //67
      content: ""
    },
    {
      prefix: "D", //68
      content: ""
    }
  ]
})


let subjectData = ref<SubjectResponse[]>([])
import type { FormRules } from 'element-plus'

//定义选项的验证规则
function checkItems(rule: any, value: any, callback: any) {
  if (value.length > 0) {
    let f = value.every((item: AnswerType) => item.content != "")
    if (f) {
      callback()
    } else {
      callback(new Error("请添加题目内容"))
    }
  } else {
    callback(new Error("请添加选项"))
  }
}
// 验证
const rules = reactive<FormRules<QuestionAddType>>({
  gradeLevel: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  subjectId: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  title: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  analyze: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  score: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  difficult: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  correct: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  items: [
    { validator: checkItems, trigger: 'blur' }
  ]
})
////////////////////////////////////
//对话框开关
let dialogVisible = ref(false)
let flag: "title" | "analyze" = "title"
// 编辑器实例
let editorInstance: any = null


function handleShow(f: "title" | "analyze") {
  flag = f
  dialogVisible.value = true
}

// 编辑器实例准备好了
function editorReady(instance: any) {
  // 保存编辑器的对象
  editorInstance = instance
  // 从params取 字段默认值
  let v = form.value[flag]
  // 给富文本编辑器设置值
  editorInstance.setContent(v)
}
// 确定
function confirm() {
  // 获取富文本编辑器里面的值
  let v = editorInstance.getContent();
  // 赋值给表单元素
  form.value[flag] = v;
  // 关闭对话框
  dialogVisible.value = false
}

//////////////////////////////////////////////
//初始化表单
function getList() {
  const id = route.query.id
  if (id) {
    loading.value = true
    ExamAPI.searchQuestionById(id as string).then(res => {
      console.log(res)
      form.value = res
    }).finally(() => {
      loading.value = false
    })
  }
}

//初始化学科
const selectSubject = ref<SubjectResponse[]>([])
function getSubject() {
  ExamAPI.getSubject().then(res => {
    subjectData.value = res
    selectSubject.value = res
    // console.log(subjectData.value);
  })
}

//提交功能
const onSubmit = () => {
  ExamAPI.questionAdd(form.value).then(() => {
    // console.log(res);
    ElMessage({
      message: '成功',
      type: 'success',
    })
    resetForm()
    router.push('/exam/question')
  })
}

//年级变化自动筛选可选学科
function handleChange(v: string | number | null | undefined) {
  if (v) {
    selectSubject.value = subjectData.value.filter(item => item.level == v)
  } else {
    selectSubject.value = [...subjectData.value]
  }
}

//删除功能
function deleteItem(index: number) {
  form.value.items.splice(index, 1)
  form.value.items.forEach((item, index) => {
    item.prefix = String.fromCharCode("A".charCodeAt(0) + index)
  })
}

//添加功能
function add() {
  let lastItem = form.value.items.at(-1)?.prefix.charCodeAt(0)
  if (lastItem) {
    form.value.items.push({
      prefix: String.fromCharCode(lastItem + 1),
      content: ""
    })
  } else {
    form.value.items.push({
      prefix: "A",
      content: ""
    })
  }

}

//重置按钮
const resetForm = () => {
  form.value = {
    id: null,
    questionType: 1, // 保持题型为单选题（初始值）
    subjectId: null, // 清空学科选择
    title: "", // 清空题干
    gradeLevel: null, // 清空年级选择
    analyze: "", // 清空解析
    correctArray: [], // 清空标签
    correct: "", // 清空正确答案选择
    score: 0, // 分数恢复默认0分
    difficult: 0, // 难度恢复默认0星
    items: [
      { prefix: "A", content: "" },
      { prefix: "B", content: "" },
      { prefix: "C", content: "" },
      { prefix: "D", content: "" }
    ]
  };

  selectSubject.value = [...subjectData.value]
};

onMounted(() => {
  resetForm()
  getSubject()
  getList()
})
</script>

<style scoped lang="scss">
.studentEdit {
  padding: 20px 40px;
}
</style>
